<?php
declare (strict_types = 1);

namespace app\admin\controller;

use app\admin\lib\Excel;
use think\facade\Log;
use think\facade\View;
use think\exception\ValidateException;
class Blog
{
    //数据展示和搜索
    public function list()
    {
        $keyword = input('keyword');
        $obj = new \app\admin\model\Admin();
        $list = $obj->list($keyword);
        if ($list)
        {
            return View::fetch('admin/list',compact('list'));
        }
    }
//添加表单展示
    public function addFrom()
    {
        return View::fetch('admin/addFrom');
    }
//添加功能
    public function addUse()
    {
        $data = input();
        try {
            validate(\app\admin\validate\User::class)->check($data);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            dump($e->getError());
        }
        $obj = new \app\admin\model\Admin();
        $res = $obj->addUse($data);
        if ($res)
        {
            Log::record('添加成功');
            return redirect('list');
        }else{
            Log::record('添加失败');
            return redirect('list');
        }
    }
//删除
    public function delUse()
    {
        $id = input('id');
//        dd($id);
        $obj = new \app\admin\model\Admin();
        $res = $obj->delUse($id);
        if ($res)
        {
            echo "<script>alert('删除成功')</script>";
            return redirect('list');
        }
    }
//批量删除
 public function delAll()
    {
        $id = input('id');
        $obj = new \app\admin\model\Admin();
        $obj->delAll($id);
            return json([
               'code'=>'200',
               'data'=>'',
               'msg'=>'删除成功'
            ]);
    }
//查找
    public function findUse()
    {
        $id = input('id');
        $obj = new \app\admin\model\Admin();
        $data = $obj->findUse($id);
        if ($data)
        {
            return View::fetch('admin/update',compact('data'));
        }
    }
//修改
    public function updateUse()
    {
        $data = input();
//        dd($data);
        $obj = new \app\admin\model\Admin();
        $res = $obj->updateUse($data);
        if ($res)
        {
            return redirect('list');
        }
    }
//excel导出
    public function get()
    {
        // 设置表格的表头数据
        $header = ["A1" => "编号", "B1" => "姓名", "C1" => "年龄"];
        // 假设下面这个数组从数据库查询出的二维数组
        $data = [
            [1,'小明',18],
            [2,'小太',19],
            [3,'小个',22],
            [4,'小贝',19],
            [5,'小东',29]
        ];
        // 保存文件的类型
        $type= true;
        // 设置下载文件保存的名称
        $fileName = '信息导出'.time();
        // 调用方法导出excel
        Excel::export($header,$type,$data,$fileName);
    }
}
